<template>
  <div class="inf-container">
    <div class="top-card">
      <el-card class="box-card">
        <el-descriptions title="账号信息">
          <el-descriptions-item label="账号">{{ admin.username }}</el-descriptions-item>
          <el-descriptions-item label="身份">{{ admin.role }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ admin.email }}
            <el-button style="margin-left: 10px;" type="text" size="mini"
              @click="dialogFormVisible = true">更换邮箱</el-button>
          </el-descriptions-item>
          <el-descriptions-item label="文章"><i style="color: red;">{{ authorList.articlesNum }}</i></el-descriptions-item>
          <el-descriptions-item label="获赞"><i style="color: red;">{{ authorList.likesNum }}</i></el-descriptions-item>
          <el-descriptions-item label="粉丝"><i style="color: red;">{{ authorList.fansNum }}</i></el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>基本信息</span>
          <el-button v-if="enable == true" style="float: right; padding: 0 10px" @click="cancel"
            type="text">取消</el-button>
          <el-button v-if="enable == true" style="float: right; padding: 0 10px" @click="edite"
            type="text">确定</el-button>
          <el-button v-if="enable == false" style="float: right; padding: 3px 0" @click="enable = true"
            type="text">修改基本信息</el-button>
        </div>
        <el-form style=" display: flex; justify-content: center; align-items: center;" :rules="rules" label-width="60px"
          :model="form" ref="form">
          <el-form-item style="width: 40%;">
            <p style="display: flex;justify-content: center;align-items: center;">
              <el-upload :disabled="!enable" class="picture-uploader" action="#" :http-request="uploadRequest"
                :show-file-list="false" :before-upload="beforeAvatarUpload">
                <img v-if="admin.avatar" :src="form.avatar" class="avatar">
                <i v-else class="avatar">上传头像</i>
              </el-upload>
            </p>
          </el-form-item>
          <el-form-item style="width: 30%;" class="inf-form" label="昵称" prop="nickname">
            <el-input size="small" style="width: auto;" v-model="form.nickname" :disabled="!enable"></el-input>
          </el-form-item>
          <el-form-item style="width: 30%;" class="inf-form" label="电话" prop="phone">
            <el-input size="small" style="width: auto;" v-model="form.phone" :disabled="!enable"></el-input>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-dialog :visible.sync="dialogFormVisible" @close="closeEditeEmail">
      <el-form :model="form" ref="form2" :rules="rules2">
        <el-form-item prop="email">
          <EmailVal v-model="form.email"></EmailVal>
        </el-form-item>
        <el-form-item prop="newEmail">
          <el-input size="medium" v-model="form.newEmail" placeholder="输入新邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="val">
          <el-input size="medium" v-model="form.val" placeholder="输入验证码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditeEmail">取 消</el-button>
        <el-button size="small" type="primary" @click="editEmail">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { updateInfAPI, updateEmailAPI, getMyDetailAPI } from '@/api/inf'
import { upload } from '@/api/web'
import EmailVal from '@/components/EmailVal'
export default {
  components: {
    EmailVal
  },
  data() {
    return {
      authorList: [],//作者信息
      admin: JSON.parse(localStorage.getItem('user')),
      enable: false,
      dialogFormVisible: false,
      form: {
        id: '',
        val: '',
        username: '',
        email: '',
        newEmail: '',
        nickname: '',
        avatar: '',
        phone: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: '输入11个数字', trigger: 'change' }
        ],
      },
      rules2: {
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        newEmail: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        val: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
        ]
      }
    }
  },
  mounted() {
    this.resetForm()
    this.getUserDetail()

  },
  methods: {
    // 获取用户信息
    async getUserDetail() {
      const res = await getMyDetailAPI()
      this.authorList = res.data[0]
    },
    // 修改邮箱
    editEmail() {
      this.$refs.form2.validate(async (valid) => {
        if (valid) {
          this.$confirm("你确定要更改邮箱?").then(async () => {
            const res = await updateEmailAPI(this.form)
            if (res.code === '200') {
              // 重新读取数据
              this.reSetLocalStorage()
            } else {
              this.$message.error(res.msg)
            }
            this.closeEditeEmail()
          })
        }
      })
    },
    closeEditeEmail() {
      this.form.newEmail = '',
        this.form.val = '',
        this.dialogFormVisible = false
      this.$refs.form2.clearValidate();
    },
    // 上传文件
    async uploadRequest(data) {
      const file = data.file
      // 处理formData类型参数
      const formData = new FormData()
      formData.append('file', file)
      const res = await upload(formData)
      if (res.code === '200') {
        this.$message.success("上传成功")
        this.form.avatar = res.data
      } else {
        this.$message.error("上传失败")
      }
    },
    // 上传文件前检查
    beforeAvatarUpload(file) {
      const isJPGandPNG = (file.type === 'image/jpeg') || (file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGandPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPGandPNG && isLt2M;
    },
    // 重置数据
    resetForm() {
      this.form.email = this.admin.email
      this.form.nickname = this.admin.nickname
      this.form.phone = this.admin.phone
      this.form.avatar = this.admin.avatar
      this.form.val = ''
      this.form.newEmail = ''
      this.form.avatar = this.admin.avatar
      this.$refs.form.clearValidate();
    },
    // 取消按钮
    cancel() {
      this.resetForm()
      this.enable = false
    },
    // 修改信息
    edite() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.$confirm("你确定要更改?").then(async () => {
            const res = await updateInfAPI(this.form)
            if (res.code == 200) {
              this.enable = false
              // 重新读取数据
              this.reGetLocalStorage()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      });

    },
    // 信息修改后，重新读取本地的值
    reGetLocalStorage() {
      this.admin.nickname = this.form.nickname ? this.form.nickname : this.admin.nickname
      this.admin.phone = this.form.phone ? this.form.phone : this.admin.phone
      this.admin.avatar = this.form.avatar ? this.form.avatar : this.admin.avatar
      this.admin.email = this.form.newEmail ? this.form.newEmail : this.admin.email
      this.admin.role = this.admin.role
      this.admin.username = this.admin.username
      localStorage.removeItem('user')
      localStorage.setItem('user', JSON.stringify(this.admin))
      this.resetForm()
      window.location.reload(); // 刷新页面
    },
  }
}
</script>

<style>
.el-message-box {
  width: 300px;
}

.inf-container {
  display: flex;
  justify-content: center;
  align-items: center;

  .el-descriptions__body .el-descriptions__table .el-descriptions-item__cell {
    line-height: 2.1;
  }

  .el-dialog {
    width: 30%;
  }

  .avatar {
    border-radius: 50%;
    width: 100px;
    height: 100px;
    display: block;
  }

  .el-input.is-disabled .el-input__inner {
    border: 0;
    background-color: #FFFFFF;
    color: #050506;
  }

  .inf-form {
    padding: 0 30px;
  }

  .box-card {
    margin: 20px;
  }
}
</style>
